//
//  YWProfileViewController.m
//  maintain
//
//  Created by 郑想 on 15/10/9.
//  Copyright (c) 2015年 ewin. All rights reserved.
//
#import "UIView+Extension.h"
#import "UIColor+CustomColors.h"
#import "UIImageView+WebCache.h"
#import "YWNavigationController.h"
#import "YWCommonTool.h"
#import "NSDate+Additions.h"
#import "YWConst.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWMacro.h"

#import "YWNotifyManager.h"
#import "QRCodeReaderViewController.h"
#import "YWAttendanceViewController.h"
#import "YWLocationManager.h"
//#import "YWMeterHomePageViewController.h"
#import "YWMeterHomeViewController.h"
#import "YWProfileCustomView.h"
#import "YWProfileViewController.h"
#import "YWSelfInfoViewController.h"
#import "UIScrollView+EmptyDataSet.h"

#import "YWScanEquipmentNotMatchVC.h"
#import "YWQrcodeInfo.h"
#import "YWQrcodeManager.h"
#import "YWMyAttendanceViewController.h"
#import "YWContactViewController.h"
#import "YWInformationBankTableViewController.h"
#import "YWRemindListTableViewController.h"

#import "YWWorkReminderManager.h"
#import "YWNoticeTableViewController.h"
#import "YWWorkNoticeViewController.h"
#import "YWMissionManager.h"
#import "YWMaterialListTableViewController.h"
#import "YWDetectAndUpkeepViewController.h"
#import "YWMyPostTroublesViewController.h"
#import "YWTroubleMissionsViewController.h"
#import "YWKeepWatchMissionViewController.h"
#import "YWInspectionMissionsViewController.h"
#import "YWSelectRecordsViewController.h"
#import "YWAssetsInventoryListTableViewController.h"
#import "YWNoReadReplyTableViewController.h"
//#import "YWNoQrcodeLedgerViewController.h"
#import "YWLedgerViewController.h"
#import "YWReplyManager.h"
#import "YWProfileHeadView.h"
#import "YWUnReadCount.h"
#import "YWEwinManager.h"
#import "YWGrabTroubleBillTableViewController.h"
#import "YWMonitorAlarmTableViewController.h"
#import "YWFunctionManager.h"
#import "YWFunctionModel.h"
#import "YWSettingsViewController.h"

#define KCountOfRow 4
#define KItemViewSize SCREEN_WIDTH / KCountOfRow

@interface YWProfileViewController () <DZNEmptyDataSetDelegate, DZNEmptyDataSetSource,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate, YWProfileCustomViewDelegate,YWProfileHeadViewDelegate>{
    UILabel *yellowSpotLabel;
}
@property (nonatomic, strong) UITableView* tableView;
@property (nonatomic, strong) NSArray* sourceDatas;
@property (nonatomic, strong) UIView* itemsView;
@property (nonatomic, strong) UIImageView *iconImageView;

//@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *scanButton;

@property (nonatomic, assign) NSInteger unReadReminderCount;
@property (nonatomic, assign) NSInteger unReadReplysCount;
@property (nonatomic, assign) NSInteger uploadFailedCount;
@property (nonatomic, assign) NSInteger unReadMonitorAlarmCount;
//@property (nonatomic, strong) NSDate *myDate;

//@property (nonatomic, strong) UIButton *rightButton;

@property (nonatomic, strong) YWProfileHeadView *headView;
@end

@implementation YWProfileViewController
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad{
    [super viewDidLoad];
    YWLoginUser *currentUser = [YWLoginTool loginUser];
    self.title = currentUser.simpleName.length?currentUser.simpleName:@"易维保";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    _unReadReminderCount = [YWLoginTool WorkReminderNoRedCount];
    _unReadMonitorAlarmCount = [YWLoginTool monitorAlarmNoRedCount];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"profile_setting"] style:UIBarButtonItemStylePlain target:self action:@selector(clickSettings:)];
    //[[UIBarButtonItem alloc] initWithTitle:@"设置" style:UIBarButtonItemStylePlain target:self action:@selector(clickSettings:)];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.iconImageView];
    
    [self.view addSubview:self.headView];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.scanButton];
    
    [self setupNotifications];
    //开启定位服务
    [[YWLocationManager shareManager] startMapLocationSever];
}

-(void)setupNotifications{
    [[YWNotifyManager shareManager] addModifySelfHeadIconObserver:self selector:@selector(modifySelfHeadIcon)];
    [[YWNotifyManager shareManager] addPushNoticeObserver:self selector:@selector(refreshNoticeRedCount:)];
    [[YWNotifyManager shareManager] addPushTempMissionObserver:self selector:@selector(refreshTempMissionRedCount:)];
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTheLatestWorkReminderFromNotification:) name:KPostRefreshTheLatestWorkReminderNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showOrHiddenYellowSpot) name:KPostShowBellYellowSpotNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showGrabTroubleBillTotalCount:) name:KPostGrabTroubleBillTotalCountNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showGrabTroubleBillTotalCount:) name:KPostGrabTroubleBillSuccessNotification object:nil];
    
    [[YWNotifyManager shareManager] addAssignDetectMissionObserver:self selector:@selector(refreshDetectRedCount:)];
    [[YWNotifyManager shareManager] addAssignUpKeepMissionObserver:self selector:@selector(refreshUpKeepRedCount:)];
    [[YWNotifyManager shareManager] addRequestTroubleMissionObserver:self selector:@selector(refreshTroubleRedCount:)];
    [[YWNotifyManager shareManager] addAssignInspectMissionObserver:self selector:@selector(refreshInspectionRedCount:)];
    [[YWNotifyManager shareManager] addAssignKeepWatchMissionObserver:self selector:@selector(refreshKeepWatchRedCount:)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshReportTroubleNoReadCount:) name:KPostReportTroubleNoReadCountNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMaterialNoReadCount:) name:KPostMaterialNoReadCountNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshAssetsInventoryNoReadCount:) name:KPostAssetsInventoryNoReadCountNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUnreadReplyCount) name:KPostRefreshUnreadReplyNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshFunctionArray) name:KPostFunctionChangeNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshReminderUnreadCount) name:KPostWorkRmindUnReadCountNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMonitorAlarmUnreadCount) name:KPostMonitorAlarmUnReadCountNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeOrganizationSuccess) name:KPushchangeOrganizationSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshRemindOfUploadFailedCount) name:KPushBackgroundUploadRecordSuccessNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    UINavigationBar *navigationBar = self.navigationController.navigationBar;
    if (navigationBar.translucent || navigationBar.shadowImage == nil) {
        [navigationBar setTranslucent:NO];
        // 导航条颜色
        [navigationBar setBarTintColor:[UIColor colorWithHex:@"353d40"]];
        [navigationBar setTintColor:[UIColor whiteColor]];
        // 导航条背景透明
        [navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
        [navigationBar setShadowImage:[[UIImage alloc] init]];
    }
    
    //未读评论
    _unReadReplysCount = [[YWReplyManager shareManager] noReadReplysCountWithRelationType:YWReplyRelationTypeAll];
    //离线记录
    BOOL isExist = [[YWWorkReminderManager shareManager] existUploadFailedMissions];
    _uploadFailedCount = isExist ? 1 : 0;
    //未读提醒数量
    _unReadReminderCount = [YWLoginTool WorkReminderNoRedCount];
    _headView.workReminderCount = _unReadReminderCount + _unReadReplysCount + _uploadFailedCount;
    self.navigationController.view.userInteractionEnabled = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.navigationController.view.userInteractionEnabled = YES;
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    self.navigationController.view.userInteractionEnabled = YES;
}

#pragma mark - Init mothods
-(UITableView *)tableView{
    if (!_tableView) {
        CGFloat headViewMaxY = CGRectGetMaxY(self.headView.frame);
        CGFloat headViewHeight = CGRectGetHeight(self.headView.frame);
        UITableView* tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headViewMaxY, SCREEN_WIDTH, SCREEN_HEIGHT-64-headViewHeight) style:UITableViewStyleGrouped];
        tableView.backgroundColor = [UIColor customBackgroudColor];
        tableView.separatorColor = [UIColor customLineColor];
        tableView.sectionFooterHeight = 1.0;
        tableView.delegate = self;
        tableView.dataSource = self;
        //tableView.tableFooterView = [[UIView alloc] init];
        tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
        [self.view addSubview:tableView];
        _tableView = tableView;
        _tableView.emptyDataSetDelegate = self;
        _tableView.emptyDataSetSource = self;
    }
    return _tableView;
}

- (YWProfileHeadView *)headView{
    if (!_headView) {
        _headView = [[YWProfileHeadView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, (SCREEN_WIDTH - 20*6) / 3 + 20+20+5)];
        _headView.workReminderCount = _unReadReminderCount + _unReadReplysCount;
        YWUnReadCount *totalCount = [[YWEwinManager shareManager] totalCount];
        _headView.troubleBillCount = totalCount.unDistributionTroubleTotal;
        _headView.monitorAlarmCount = _unReadMonitorAlarmCount;
        _headView.delegate = self;
    }
    return _headView;
}

- (NSArray*)sourceDatas
{
    if (!_sourceDatas) {
        NSString *noticeNoRed = [NSString stringWithFormat:@"%ld",(long)[YWLoginTool noticeNoRedCount]];
        NSString *tempMissionNoRed = [NSString stringWithFormat:@"%ld",(long)[YWLoginTool tempMissionNoRedCount]];
        NSString *detectMissionNoRed = [NSString stringWithFormat:@"%ld",(long)[YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeDetection]];
        NSString *upkeepMissionNoRed = [NSString stringWithFormat:@"%ld",(long)[YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeUpkeep]];
        NSString *troubleMissionNoRed = [NSString stringWithFormat:@"%ld",(long)[YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeTrouble]];
        NSString *inspectionMissionNoRed = [NSString stringWithFormat:@"%ld",(long)[YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypePatrol]];
        NSString *keepWatchMissionNoRed = [NSString stringWithFormat:@"%ld",(long)[YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeKeepWatch]];
        NSArray* footerSourceDatas = [[YWFunctionManager shareManager] getFunctionMenuWithOffOrOn:YWFunctionStatusOn isSetting:NO];
        for (YWFunctionModel * function in footerSourceDatas) {
            if (function.functionId == YWFunctionIdEquipmentLedger) {
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"equipmentLedger", nil);
            }else if (function.functionId == YWFunctionIdPostTrouble){
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"postTrouble", nil);
            }else if (function.functionId == YWFunctionIdKeepWatch){
                function.redCount = keepWatchMissionNoRed;
                function.functionName = NSLocalizedString(@"keepWatch", nil);
            }else if (function.functionId == YWFunctionIdInspection){
                function.redCount = inspectionMissionNoRed;
                function.functionName = NSLocalizedString(@"inspection", nil);
            }else if (function.functionId == YWFunctionIdDetection){
                function.redCount = detectMissionNoRed;
                function.functionName = NSLocalizedString(@"detection", nil);
            }else if (function.functionId == YWFunctionIdUpkeep){
                function.redCount = upkeepMissionNoRed;
                function.functionName = NSLocalizedString(@"upkeep", nil);
            }else if (function.functionId == YWFunctionIdRepair){
                function.redCount = troubleMissionNoRed;
                function.functionName = NSLocalizedString(@"trouble", nil);
            }else if (function.functionId == YWFunctionIdRecords){
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"record", nil);
            }else if (function.functionId == YWFunctionIdCheckRecord){
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"checkRecord", nil);
            }else if (function.functionId == YWFunctionIdMaterial){
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"material", nil);
            }else if (function.functionId == YWFunctionIdShuidianmei){
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"meterReading", nil);
            }else if (function.functionId == YWFunctionIdAttendance){
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"attendance", nil);
            }else if (function.functionId == YWFunctionIdNotice){
                function.redCount = noticeNoRed;
                function.functionName = NSLocalizedString(@"notice", nil);
            }else if (function.functionId == YWFunctionIdTempMission){
                function.redCount = tempMissionNoRed;
                function.functionName = NSLocalizedString(@"tempMission", nil);
            }else if (function.functionId == YWFunctionIdAddressBook){
                function.redCount = @"0";
                function.functionName = NSLocalizedString(@"addressBook", nil);
            }
        }
        _sourceDatas = footerSourceDatas;
    }
    return _sourceDatas;
}

- (UIView*)itemsView
{
    if (!_itemsView) {
        NSInteger dataCount = self.sourceDatas.count;
        NSInteger row = ((dataCount-1)/KCountOfRow+1);
        
        CGFloat height = KItemViewSize*row;
        UIView* itemsView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, height)];
        itemsView.backgroundColor = [UIColor whiteColor];
        for (int i = 0; i < self.sourceDatas.count; i++) {
            YWProfileCustomView *customView = [[YWProfileCustomView alloc]init];
            
            YWFunctionModel * function = self.sourceDatas[i];
            CGSize size = [YWCommonTool getSizeOfLabel:function.functionName andWidth:KItemViewSize andFont:kContentFont].size;
            customView.buttonLabelSize = CGSizeMake(size.width, size.height);
            customView.frame = CGRectMake(KItemViewSize * (i % KCountOfRow), (i / KCountOfRow) * KItemViewSize, KItemViewSize, KItemViewSize);
            customView.function = function;
            customView.tag = function.functionTag;

            customView.delegate = self;
            [itemsView addSubview:customView];
        }
        
        if (dataCount>0) {
            for (int i=1; i <= row; i++) {
                //划横线
                [itemsView addSubview:[YWCommonTool lineOfView:CGRectMake(0, KItemViewSize*i, SCREEN_WIDTH, 0.5)]];
            }
            CGFloat lineHeight = KItemViewSize*row;
            for (int i=1; i<KCountOfRow; i++) {
                //划竖线
                if (dataCount>=i) {
                    [itemsView addSubview:[YWCommonTool lineOfView:CGRectMake(KItemViewSize*i, 0, 0.5, lineHeight)]];
                }
            }
        }
        
        _itemsView = itemsView;
    }
    return _itemsView;
}

-(UIButton *)scanButton{
    if (!_scanButton) {
        UIButton* scanButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [scanButton setImage:[UIImage imageNamed:@"temp_scanButton"] forState:UIControlStateNormal];
        scanButton.layer.masksToBounds = YES;
        [scanButton addTarget:self action:@selector(handleScanButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        scanButton.frame = CGRectMake((SCREEN_WIDTH-50)/2, SCREEN_HEIGHT-64-50, 50, 50);
        _scanButton = scanButton;
    }
    return _scanButton;
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.sourceDatas count] ? 1 : 0;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    static NSString* identifier = @"YWProfileTableViewContentCellIdentifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [cell.contentView addSubview:self.itemsView];
    return cell;
}

#pragma mark - UITableViewDataDelegate mothods
- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    CGFloat height = KItemViewSize * ((self.sourceDatas.count-1) / KCountOfRow + 1);
    return height;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    return kLabelH;//kLabelH+10;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)clickWorkRminderEvent:(id)sender{
    YWRemindListTableViewController *remindListVC = [[YWRemindListTableViewController alloc] init];
//    remindListVC.clearUnReadReplysCountBlock = ^() {
//        _unReadReplysCount = 0;
//        _headView.workReminderCount = _unReadWorkReminderCount + _unReadReplysCount + _uploadFailedCount;
//    };
    [self.navigationController pushViewController:remindListVC animated:YES];
//    [YWLoginTool clearWorkReminderNoRedCount];
//    _unReadReplysCount = 0;
//    _headView.workReminderCount = _unReadReminderCount + _unReadReplysCount + _uploadFailedCount;
}

- (void)clickGrabBillEvent:(id)sender{
    //抢单
    YWGrabTroubleBillTableViewController *grabTroubleBillVC = [[YWGrabTroubleBillTableViewController alloc] init];
    [self.navigationController pushViewController:grabTroubleBillVC animated:YES];
}

- (void)clickMonitorAlarmEvent:(id)sender{
    //监控报警
    YWMonitorAlarmTableViewController *monitorAlarmTableVC = [[YWMonitorAlarmTableViewController alloc] init];
    [self.navigationController pushViewController:monitorAlarmTableVC animated:YES];
    [YWLoginTool clearMonitorAlarmNoRedCount];
    _headView.monitorAlarmCount = 0;
}

- (void)showOrHiddenYellowSpot{
    yellowSpotLabel.hidden = NO;
}

- (void)showGrabTroubleBillTotalCount:(id)sender{
    YWUnReadCount *totalCount = [[YWEwinManager shareManager] totalCount];
    _headView.troubleBillCount = totalCount.unDistributionTroubleTotal;
}

- (void)refreshNoticeRedCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagNotice];
    NSInteger count = [YWLoginTool noticeNoRedCount];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshTempMissionRedCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagTempMission];
    NSInteger count = [YWLoginTool tempMissionNoRedCount];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshDetectRedCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagDetection];
    NSInteger count = [YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeDetection];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshUpKeepRedCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagUpkeep];
    NSInteger count = [YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeUpkeep];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshTroubleRedCount:(NSNotification*)noti{
    NSInteger troubleId = [noti.object integerValue];
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagRepair];
    NSInteger count = [YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeTrouble];
    if (count >0 || troubleId == 0) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshInspectionRedCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagInspection];
    NSInteger count = [YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypePatrol];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshKeepWatchRedCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagKeepWatch];
    NSInteger count = [YWLoginTool missionNoRedCountWithMaintenanceType:YWMaintenanceTypeKeepWatch];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshReportTroubleNoReadCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagPostTrouble];
    NSInteger count = [YWLoginTool reportTroubleNoReadCount];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshMaterialNoReadCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagMaterial];
    NSInteger count = [YWLoginTool materialNoReadCount];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshAssetsInventoryNoReadCount:(BOOL)isClean{
    YWProfileCustomView* view = [self.itemsView viewWithTag:YWFunctionTagCheckRecord];
    NSInteger count = [YWLoginTool assetsInventoryNoReadCount];
    if (count >0 || isClean) {
        view.noRedCount = [@(count) stringValue];
    }
}

- (void)refreshReminderUnreadCount{
    _unReadReminderCount = [YWLoginTool WorkReminderNoRedCount];
    _headView.workReminderCount = _unReadReminderCount + _unReadReplysCount + _uploadFailedCount;
}

- (void)refreshMonitorAlarmUnreadCount{
    _unReadMonitorAlarmCount = [YWLoginTool monitorAlarmNoRedCount];
    if (_unReadMonitorAlarmCount>0) {
        _headView.monitorAlarmCount = _unReadMonitorAlarmCount;
    }
}

- (void)refreshUnreadReplyCount{
    NSInteger unReadCount = [[YWReplyManager shareManager] noReadReplysCountWithRelationType:YWReplyRelationTypeAll];
    _unReadReplysCount = unReadCount;
    _headView.workReminderCount = _unReadReminderCount + _unReadReplysCount + _uploadFailedCount;
}

- (void)refreshRemindOfUploadFailedCount{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //离线记录
        BOOL isExist = [[YWWorkReminderManager shareManager] existUploadFailedMissions];
        _uploadFailedCount = isExist ? 1 : 0;
        _headView.workReminderCount = _unReadReminderCount + _unReadReplysCount + _uploadFailedCount;
    });
}

- (void)refreshFunctionArray{
    _sourceDatas = nil;
    [_itemsView removeFromSuperview];
    _itemsView = nil;
    [self.tableView reloadData];
}

- (UIImageView *)iconImageView{
    if (!_iconImageView) {
        UIImageView* iconImageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 32, 32)];
        YWLoginUser* loginUser = [YWLoginTool loginUser];
        NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, loginUser.headIcon];
        [iconImageV sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"profile_headimage"] ];
        iconImageV.layer.masksToBounds = YES;
        iconImageV.layer.cornerRadius = 32/2;
        
        iconImageV.contentMode = UIViewContentModeScaleAspectFill;
        [iconImageV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleIconTapEvent:)]];
        _iconImageView = iconImageV;
    }
    return _iconImageView;
}

- (void)modifySelfHeadIcon{
    //修改个人头像
    YWLoginUser* loginUser = [YWLoginTool loginUser];
    NSString* urlStr = [NSString stringWithFormat:@"%@%@", kAliyunImageUrl, loginUser.headIcon];
    [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"profile_headimage"]];
}

- (void)changeOrganizationSuccess{
    YWLoginUser *currentUser = [YWLoginTool loginUser];
    self.title = currentUser.simpleName.length?currentUser.simpleName:@"易维保";
    
    [self modifySelfHeadIcon];
}

#pragma mark - YWProfileCustomViewDelegate
- (void)clickItemButtonWithTag:(NSInteger)tag
{
    switch (tag) {
        case 0: {
            //设备台账
            YWLedgerViewController * noQrcodeLedgerVC = [[YWLedgerViewController alloc] init];
            [self.navigationController pushViewController:noQrcodeLedgerVC animated:YES];
        } break;
        case 1: {
            //报障
            YWMyPostTroublesViewController *myTroublesVC = [[YWMyPostTroublesViewController alloc]init];
            [self.navigationController pushViewController:myTroublesVC animated:YES];
            [YWLoginTool clearReportTroubleNoReadCount];
            [self refreshReportTroubleNoReadCount:YES];
            
        } break;
        case 2: {
            //巡更
            YWKeepWatchMissionViewController* keepWatchVC = [[YWKeepWatchMissionViewController alloc] init];
            [self.navigationController pushViewController:keepWatchVC animated:YES];
            [YWLoginTool clearMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeKeepWatch];
            [self refreshKeepWatchRedCount:YES];
        } break;
        case 3:{
            //巡查
            YWInspectionMissionsViewController *inspectionMissionVC = [[YWInspectionMissionsViewController alloc]init];
            [self.navigationController pushViewController:inspectionMissionVC animated:YES];
            [YWLoginTool clearMissionNoRedCountWithMaintenanceType:YWMaintenanceTypePatrol];
            [self refreshInspectionRedCount:YES];
        } break;
        case 4:{
            //检测
            YWDetectAndUpkeepViewController* maintenceVC = [[YWDetectAndUpkeepViewController alloc] init];
            maintenceVC.maintenanceType = YWMaintenanceTypeDetection;
            [self.navigationController pushViewController:maintenceVC animated:YES];
            [YWLoginTool clearMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeDetection];
            [self refreshDetectRedCount:YES];
        } break;
        case 5: {
            //保养
            YWDetectAndUpkeepViewController* maintenceVC = [[YWDetectAndUpkeepViewController alloc] init];
            maintenceVC.maintenanceType = YWMaintenanceTypeUpkeep;
            [self.navigationController pushViewController:maintenceVC animated:YES];
            [YWLoginTool clearMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeUpkeep];
            [self refreshUpKeepRedCount:YES];
        } break;
        case 6: {
            //维修
            YWTroubleMissionsViewController* troubleVC = [[YWTroubleMissionsViewController alloc] init];
            [self.navigationController pushViewController:troubleVC animated:YES];
            [YWLoginTool clearMissionNoRedCountWithMaintenanceType:YWMaintenanceTypeTrouble];
            [self refreshTroubleRedCount:nil];
        } break;
        case 7: {
            //记录
            YWSelectRecordsViewController *selectRecordVC = [[YWSelectRecordsViewController alloc] init];
            [self.navigationController pushViewController:selectRecordVC animated:YES];
        } break;
        case 8: {
            //清点
            YWAssetsInventoryListTableViewController *assetsInventory = [[YWAssetsInventoryListTableViewController alloc]init];
            [self.navigationController pushViewController:assetsInventory animated:YES];
            [YWLoginTool clearAssetsInventoryNoReadCount];
            [self refreshAssetsInventoryNoReadCount:YES];
        } break;
        case 9: {
            //物料管理
            YWMaterialListTableViewController *materialListVC = [[YWMaterialListTableViewController alloc] init];
            [self.navigationController pushViewController:materialListVC animated:YES];
            [YWLoginTool clearMaterialNoReadCount];
            [self refreshMaterialNoReadCount:YES];
        } break;
        case 10: {
            //抄表
            YWMeterHomeViewController* meterHomePageViewController = [[YWMeterHomeViewController alloc] init];
            [self.navigationController pushViewController:meterHomePageViewController animated:YES];
        } break;
        case 11: {
            //签到
            YWMyAttendanceViewController *myAttendanceVC = [[YWMyAttendanceViewController alloc]init];
            [self.navigationController pushViewController:myAttendanceVC animated:YES];
        } break;
        case 12: {
            //通知
            YWNoticeTableViewController *noticeVC = [YWNoticeTableViewController new];
            [self.navigationController pushViewController:noticeVC animated:YES];
            [YWLoginTool clearNoticeNoRedCount];
            [self refreshNoticeRedCount:YES];
        } break;
        case 13: {
            //临时任务
            YWWorkNoticeViewController *tempMissionVC = [YWWorkNoticeViewController new];
            [self.navigationController pushViewController:tempMissionVC animated:YES];
            [YWLoginTool clearTempMissionNoRedCount];
            [self refreshTempMissionRedCount:YES];
        } break;
        case 14: {
            //通讯录
            YWContactViewController* contactVC = [[YWContactViewController alloc] init];
            [self.navigationController pushViewController:contactVC animated:YES];
        } break;
        case 15: {
            //资料库
            YWInformationBankTableViewController *informationBankVC = [[YWInformationBankTableViewController alloc]init];
            [self.navigationController pushViewController:informationBankVC animated:YES];
        } break;
        default:
            break;
    }
}

- (void)handleIconTapEvent:(id)sender{
    YWSelfInfoViewController *selfInfoVC = [[YWSelfInfoViewController alloc]init];
    [self.navigationController pushViewController:selfInfoVC animated:YES];
}

- (void)handleScanButtonEvent:(id)sender{
    [[YWQrcodeManager shareManager] clickScanButtonWithType:YWQrcodeScanTypeNomall ViewController:self completionBlock:^(NSString *qrcodeId, QRCodeReaderViewController *qrCodeReaderViewController) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [qrCodeReaderViewController dismissViewControllerAnimated:NO completion:^{
                [self qrcodeSuccessWithQrcodeID:qrcodeId];
            }];
        });
    }];
}

-(void)qrcodeSuccessWithQrcodeID:(NSString*)qrCodeId{
    YWLedgerViewController * noLedgerVC = [[YWLedgerViewController alloc] init];
    NSArray *matchMission = [[YWMissionManager shareManager] matchAllTypeMissionsWithQrcodeId:qrCodeId];
    noLedgerVC.matchMissions = matchMission;
    noLedgerVC.qrcodeId = qrCodeId;
    [self.navigationController pushViewController:noLedgerVC animated:YES];
}

- (void)clickSettings:(id)sender{
    YWSettingsViewController *settingsVC = [[YWSettingsViewController alloc]init];
    [self.navigationController pushViewController:settingsVC animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
